var obj;
window.onload=function () {
    obj=new Table();
    obj.tableInit();
    obj.tableInit2();

    //选择时间触发事件
    document.getElementById("currentDate").addEventListener("blur",function (e) {
        var val = this.value.split("-");
        obj.year=parseInt(val[0]);
        obj.month=parseInt(val[1]);
    })
}

//绩效数据事件
function toLoadJxAssessWlbPjz(){
    var year=obj.year;
    var month=obj.month;
    if (!year){
        windowsOperation(null,null,{status:200,msg:"请先选择日期!"})
        return;
    }
    var data=commonAjax("post","/jx/wlb/queryJxAssessWlbYcl",{year:year,month:month,type:obj.type})
    $("#dg").datagrid("loadData",data.a);
    $("#dg2").datagrid("loadData",data.b);
    $("#totalMoney").val(data.money);
}

//表字段
function tableColumns(val) {
    var result;
    result=[[
        {"field": 'empName', "title": '姓名', "width": '5%', "align": "center","editor": {"type": "text"}},
        {"field": 'empCode', "title": '工号', "width": '5%', "align": "center","editor": {"type": "text"}},
        {"field": 'achieving',"title": '配制车间整<br>体计划达成<br>率',"width": '5%',"align": "center",
            "editor": {"type": "textbox","options": {onChange:producePrecisionOnChange}}},
        {"field": 'punctuality',"title": '原料备料/<br>收货/入库准<br>时率',"width": '5%',"align": "center",
            "editor": {"type": "textbox", "options": {onChange:producePrecisionOnChange}}},
        {"field": 'exact',"title": '原料备料/<br>收货/入库准<br>确率',"width": '5%',"align": "center",
            "editor": {"type": "textbox", "options": {onChange:producePrecisionOnChange}}},
        {"field": 'performanceBonusNorm', "title": '综合奖金基<br>数', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {onChange:resultMoneyOnChange}}},
       {"field": 'score7S',"title": '7S分数',"width": '5%',"align": "center",
           "editor": {"type": "textbox", "options": {onChange:score7sOnChange}}},
       {"field": 'rp7S',"title": '7S得分',"width": '5%',"align": "center",
           "editor": {"type": "textbox", "options": {onChange:resultMoneyOnChange}}},
        {"field": 'attendanceRate', "title": '出勤率', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {onChange:resultMoneyOnChange}}},
        {"field": 'otherAssess', "title": '其它扣款', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {onChange:resultMoneyOnChange}}},
        {"field": 'otherAward', "title": '其它奖励', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {onChange:resultMoneyOnChange}}},
        {"field": 'resultMoney', "title": '综合<br/>绩效（元）', "width": '8%',"align": "center","editor": {"type": "textbox", "options": {"readonly":true}}},
        {"field": 'remarks', "title": '备注',"width": '29%', "align": "center","editor": {"type":"textarea"}}
    ]]
    var postName= {"field": 'postName', "title": '职务', "width": '8%', "align": "center","editor": {"type": "combobox","options": {editable:false,valueField:"v",textField:"t",
                    panelHeight:'auto',data:[{v:'仓务员',t:'仓务员'},{v:'账务员',t:'账务员'},{v:'收货员',t:'收货员'}]}}}
    var postName2= {"field": 'postName', "title": '职务', "width": '8%', "align": "center","editor": {"type": "combobox","options": {editable:false,valueField:"v",textField:"t",
                    panelHeight:'auto',data:[{v:'主管',t:'主管'},{v:'叉车司机',t:'叉车司机'},{v:'清洁工',t:'清洁工'}]}}}
    switch (val) {
        case 1:
            result[0].splice(2,0,postName);
            break
        case 2:
            result[0].splice(2,0,postName2);
            break
    }
    return result;
}

//表对象
function Table(){
    this.type=4;                    //原材料在统计表中的类型
    this.index=1;
    this.index2=1;
    this.dept='1002O110000000000ML2';   //原材料部门
    this.year="";
    this.month="";
    this.url="";
    this.data="";
    this.queryParams={};
    this.tableInit=function () {
        $('#dg').edatagrid({
            width:'100%',
            height:document.getElementById("article").clientHeight,
            url:this.url,
            queryParams:this.queryParams,
            showFooter:true,
            autoSave:true,
            nowrap:false,
            columns:tableColumns(1),
            onLoadSuccess:data=>{
                if (data.rows.length==0){
                    windowsOperation(null,null,{status:200,msg:"没有"+obj.month+"月的绩效数据！"})
                }
            },
            onBeforeEdit:function (index, row) {
                obj.index=index;
            },
            onBeginEdit:function(index,row){
                var postName=editObj("postName");
                if(!postName.textbox("getValue")){
                    postName.textbox("setValue","仓务员")
                }

            },
            onAfterEdit:function () {
                //页脚行
                calculateFooter()
                //总合计
                calculateTotal()
            }
        });
    }
    this.tableInit2=()=>{
        $('#dg2').edatagrid({
            width:'100%',
            height:document.getElementById("article2").clientHeight,
            data:this.data,
            queryParams:this.queryParams,
            showFooter:true,
            autoSave:true,
            nowrap:false,
            columns:tableColumns(2),
            onLoadSuccess:data=>{
                if (data.rows.length==0){
                    windowsOperation(null,null,{status:200,msg:"没有"+obj.month+"月的绩效数据！"})
                }
            },
            onBeforeEdit:function (index, row) {
                obj.index2=index;
            },
            onAfterEdit:function () {
                //页脚行
                calculateFooter()
                //总合计
                calculateTotal()
            }
        });
    }

    //计算页脚行
    function calculateFooter() {
        //获取所有的行
        var rows=$("#dg").datagrid("getRows");
        var resultMoney=0;
        var pcsTotal=0;
        var temp2=0;
        rows.forEach(function (val) {
            var r = val.resultMoney;
            r=r?Number(r):0;
            var postName = val.postName;
            switch (postName) {
                case "仓务员":
                case "收货员":
                    pcsTotal+= r
                    temp2++;
                break;
            }
            if (r){
                resultMoney+=r;
            }
        })
        //统计
        //重新加载页脚行
        $('#dg').datagrid('reloadFooter',[
            {empCode: '仓务员/收货员合计', resultMoney: fomatFloat(pcsTotal,2),total:temp2},
            {empCode: '合计', resultMoney: fomatFloat(resultMoney,2)}
        ]);
    }
}

//综合<br/>绩效（元）
function resultMoneyOnChange(){
    var performanceBonusNorm = editObj("performanceBonusNorm").textbox("getValue"); //performanceBonusNorm 综合奖金基<br>数
    performanceBonusNorm=performanceBonusNorm?Number(performanceBonusNorm):0;
    var otherAssess = editObj("otherAssess").textbox("getValue");       //其它扣款
    otherAssess=otherAssess?Number(otherAssess):0;
    var otherAward = editObj("otherAward").textbox("getValue");         //其它奖励
    otherAward=otherAward?Number(otherAward):0;
    var attendanceRate = editObj("attendanceRate").textbox("getValue"); //出勤率
    attendanceRate=attendanceRate?Number(attendanceRate)/100:0;
    var rp7s = editObj("rp7S").textbox("getValue");                     //7s得分
    rp7s=rp7s?Number(rp7s):0;
    //start 计算
    var result=0;
    var postName = editObj("postName").textbox("getValue"); //职务
    if (postName=="仓务员" || postName=="收货员"){
        //   S1=(C*90%+E*10%)*A1-D
        result=fomatFloat((performanceBonusNorm*0.9+rp7s)*attendanceRate-otherAssess+otherAward,2);
    }else if (postName=="账务员"){
        result=fomatFloat((performanceBonusNorm*0.95+rp7s)*attendanceRate-otherAssess+otherAward,2);
    }else if(postName=="主管" || postName=="叉车司机" || postName=="清洁工" ){
        result=fomatFloat(performanceBonusNorm*attendanceRate-otherAssess+otherAward,2);
    }

    var resultMoney = editObj("resultMoney"); //综合<br/>绩效（元）
    resultMoney.textbox("setValue",result)

}

//计算综合奖金基数事件
function producePrecisionOnChange(){
    var achieving = editObj("achieving").textbox("getValue");  //achieving:包装车间整体达成率
    var exact = editObj("exact").textbox("getValue");           //准确率
    var punctuality = editObj("punctuality").textbox("getValue"); //准时率
    var result=0;
    var postName=editObj("postName").textbox("getValue");
    switch (postName) {
        case "仓务员":
        case "账务员":
        case "收货员":
            if (achieving>=95 && exact==100){  //配制车间整体达成率必须大于95 并且 准确率100
                if (97<punctuality && punctuality<98){
                    result=400;
                }
                if (98<=punctuality && punctuality<100){
                    result=500;
                }

                if (punctuality==100){
                    result=600;
                }
            }
            break;
    }
    //主管和组长不用计算
    if (postName =="主管" || postName =="叉车司机" || postName == "清洁工"){
      return
    }

    var performanceBonusNorm = editObj("performanceBonusNorm");
    performanceBonusNorm.textbox("setValue",result);
}

//7s得分
function score7sOnChange(newValue) {
    var result=0;
    var performanceBonusNorm = editObj("performanceBonusNorm").textbox("getValue");
    performanceBonusNorm=performanceBonusNorm?performanceBonusNorm:0;
    var postName = editObj("postName").textbox("getValue"); //职务
    if (newValue>=75){
        switch (postName) {
            case "收货员":
            case "仓务员":
                result= Number(performanceBonusNorm)*0.1;
                break;
            case "账务员":
                result=Number(performanceBonusNorm)*0.05;
        }

    }else {
        switch (postName) {
            case "收货员":
            case "仓务员":
                result= -Number(performanceBonusNorm)*0.1;
                break;
            case "账务员":
                result= -Number(performanceBonusNorm)*0.05;
        }

    }
    editObj("rp7S").textbox("setValue",fomatFloat(result,2));
}

//加载员工事件
function toLoadEmp(){
    obj.url='/jx/wlb/selectPjzEmpNotZgAndCcAndQj';
    obj.queryParams.pkDept=obj.dept
    obj.tableInit();
}
//加载第二张表事件
function loadManager(){
    //获取数据
    var data = commonAjax("post","/jx/wlb/selectPjzEmpSoAsZgAndCcAndQj",{pkDept:obj.dept});
    //获取员工表页脚行
    var footers = $("#dg").datagrid("getFooterRows");

    data.forEach(function (v) {
        var postName = v.postName;
        if(footers){
            footers.forEach(function (val) {
                if (val.empCode=="仓务员/收货员合计"){
                    var resultMoney
                    if (postName=="主管"){
                        resultMoney=fomatFloat(Number(val.resultMoney)/val.total*1.4,2)
                        resultMoney=resultMoney>800?800:resultMoney;
                    }
                    if (postName=="叉车司机"){
                        resultMoney=fomatFloat(Number(val.resultMoney)/val.total,2)
                    }
                    if (postName=="清洁工"){
                        resultMoney=fomatFloat(Number(val.resultMoney)/val.total/2,2)

                    }
                    v.performanceBonusNorm=resultMoney;
                    return
                }

            })
        }

    })
    obj.data=data;
    obj.tableInit2();
}

//总合计计算
function calculateTotal() {
    var resultData=0;
    var dgdata=$("#dg").datagrid("getRows");
    if (dgdata){
        dgdata.forEach(function (v) {
            var resultMoney = v.resultMoney;
            resultMoney=resultMoney?Number(resultMoney):0;
            resultData=resultData+resultMoney;
        })
    }
    var dgdata2=$("#dg2").datagrid("getRows");
    if (dgdata2){
        dgdata2.forEach(function (v) {
            var resultMoney = v.resultMoney;
            resultMoney=resultMoney?Number(resultMoney):0;
            resultData=resultData+resultMoney
        })
    }
    $("#totalMoney").val(fomatFloat(resultData,2));
}

function addData() {
    //判断是否有选择日期
    var year = obj.year;
    if (!year){
        windowsOperation(null,null,{status:200,msg:"添加失败，请输入日期！"})
        return
    }
    var month = obj.month;
    var resultData;
    var rows = $("#dg").datagrid("getRows");
    var rows2 = $("#dg2").datagrid("getRows");
    for (let r of rows2){
        rows.push(r);
    }
    rows.forEach(function ( val) {
        val.assessYear=year;
        val.assessMonth=month;
    })
    //封装总合计
    var  totalMoney= $("#totalMoney").val();
    var jxAssessWlbTotal={};
    var jxAssessWlbTotals=[];
    jxAssessWlbTotal.assessYear=year;
    jxAssessWlbTotal.assessMonth=month;
    jxAssessWlbTotal.assessType=obj.type;    //配件组类型
    jxAssessWlbTotal.totalMoney=totalMoney;
    jxAssessWlbTotal.remarks="合计";
    jxAssessWlbTotals.push(jxAssessWlbTotal);
    resultData={"jxAssessWlbYcl":rows,jxAssessWlbTotals:jxAssessWlbTotals}
    resultData=JSON.stringify(resultData);
    var data= commonAjax("post","/jx/wlb/addYclData",resultData,"application/json;charset=utf-8");
    windowsOperation(null,null,data)
}

function editObj(fieldName) {
    var result;
    try {
        result= $('#dg').datagrid("getEditor",{index:obj.index,field:fieldName}).target;
    }catch (e) {
        result= $('#dg2').datagrid("getEditor",{index:obj.index2,field:fieldName}).target;
    }
    return  result;
}
